﻿//   Copyright 2009 Pyxis Technologies
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

using Pyxis.FluentSelenium.Locator;
using Selenium;

namespace Pyxis.FluentSelenium.Tester
{
    public class TableTester
    {
        private readonly TableLocator locator;
        private readonly ContentTester rootTester;
        private readonly string rowCountLocator;

        private ISelenium selenium
        {
            get { return rootTester.Selenium; }
        }

        internal TableTester(TableLocator locator, ContentTester rootTester)
        {
            this.locator = locator;
            this.rootTester = rootTester;
            rowCountLocator = string.Format("{0}/tr", GetTableBodyXPath());
        }

        public TableRowTester Row(int index)
        {
            var tableLocator = GetTableBodyXPath();
            return new TableRowTester(selenium, tableLocator, index);
        }

        public TableColumnTester Column(int columnIndex)
        {
            var tableLocator = GetTableBodyXPath();
            return new TableColumnTester(selenium, tableLocator, columnIndex);
        }

        public TableHeaderTester ColumnHeader(int columnIndex)
        {
            return TableHeaderTester.Create(selenium, locator.ToString(), columnIndex);
        }

        private string GetTableBodyXPath()
        {
            return string.Format("{0}/tbody", locator);
        }

        private int GetTableRowCount()
        {
            return (int)selenium.GetXpathCount(rowCountLocator);
        }

        public void ShouldCountRows(int rowCount)
        {
            Assert.ExpectedElementCount(rowCount, GetTableRowCount(), ElementLocator.WithXpath(rowCountLocator));
        }
    }
}
